package com.primaryedu.ui;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.primaryedu.data.HigtApplication;

/**
 * Created by Thomas_yang on 2018/9/21.
 */

public abstract class BaseFragment extends Fragment {

    protected Activity mActivity;
    private View view;
    private Toast toast;

    /**
     * 获得全局的，防止使用getActivity()为空
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity)context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container
            , Bundle savedInstanceState) {

        view = LayoutInflater.from(mActivity)
                .inflate(getLayoutId(), container, false);
        initView(view, savedInstanceState);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    /**
     * 该抽象方法就是 onCreateView中需要的layoutID
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 该抽象方法就是 初始化view
     * @param view
     * @param savedInstanceState
     */
    protected abstract void initView(View view, Bundle savedInstanceState);

    /**
     * 执行数据的加载
     */
    protected abstract void initData();

    /**
     * [绑定控件]
     *
     * @param resId
     * @return
     */
    protected <T extends View> T $(@IdRes int resId) {
        return (T) view.findViewById(resId);
    }

    /**
     * 消息提示框
     *
     * @param message 提示消息文本
     */

    protected void showToast(String message) {
//        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        try {
            if (toast != null) {
                toast.setText(message);
            } else {
                toast = Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT);
            }
            toast.show();
        } catch (Exception e) {
            // 解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            toast = Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT);
            toast.show();
            Looper.loop();
        }
    }
}
